package com.qding.park.manager.web.power;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.qding.park.common.core.annotation.MethodCacheable;
import com.qding.park.common.core.annotation.log.OperationLogType;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.auth.AuthException;
import com.qding.park.common.utils.ListUtil;
import com.qding.park.manager.pojo.LogInfo;
import com.qding.park.manager.pojo.PowerInfo;
import com.qding.park.manager.web.controller.Web_CarController;
import com.qding.smart.common.web.security.SysUserDTO;
import com.qding.smart.sso.client.entry.UserInfo;
import com.qding.smart.sso.client.util.SSOClientHelp;

@Aspect
@Component
@Order(Integer.MAX_VALUE - 1)
public class PowerAspect {

    private static final Logger _log = LoggerFactory.getLogger(PowerAspect.class);
    
    private static final String SESSION_KEY = "SMART_USER_SESSION";

    private PowerInfo getPowerInfo(HttpServletRequest request) {

        UserInfo user = SSOClientHelp.getUserInfo(request);
        PowerInfo power = new PowerInfo();
        power.setAdminIs(user.isAdaminIs());
        power.setParkList(user.getParklist());
        return power;
    }

    private String getUsername(HttpServletRequest request) {

        UserInfo user = SSOClientHelp.getUserInfo(request);

        return user.getUserName();
    }

    private Method getMethod(JoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();

        return method;

    }

    private EvaluationContext structExpContext(Method method, Object[] args) {
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paraNameArr = u.getParameterNames(method);
        StandardEvaluationContext context = new StandardEvaluationContext();
        for (int i = 0; i < paraNameArr.length; i++) {
            context.setVariable(paraNameArr[i], args[i]);
        }
        return context;

    }

    @Before("@annotation(com.qding.park.manager.web.power.Power)")
    public void doBefore(JoinPoint joinPoint) {
        Method method = getMethod(joinPoint);
        _log.info("开始进行权限判断:{},{}", joinPoint.getTarget().getClass().getName(), method.getName());
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        HttpSession session= request.getSession();
       SysUserDTO userInfo= (SysUserDTO) session.getAttribute(SESSION_KEY);
//        PowerInfo powerInfo = getPowerInfo(request);
        Power powerAnnotation = method.getAnnotation(com.qding.park.manager.web.power.Power.class);
        String parkEl = powerAnnotation.visitPark();

        ExpressionParser parser = new SpelExpressionParser();
        EvaluationContext exvContext = structExpContext(method, joinPoint.getArgs());

        String parkId = (String) parser.parseExpression(parkEl).getValue(exvContext, joinPoint.getTarget());
           
        if (StringUtils.isBlank(parkId)) {
            if (ListUtil.isEmpty(userInfo.getParkList()) && !userInfo.isAdmin()) {
                throw new AuthException(AuthException.TypeEnum.EXCEPTION_AUTH.getId(), null,
                        ExceptionMessage.createExceptionMessage(AuthException.TypeEnum.EXCEPTION_AUTH.getDesc(),
                                this.getUsername(request) + " 没有此车场的权限", "权限不足:"));
            }
        } else {
            if (!userInfo.getParkList().contains(Integer.valueOf(parkId)) && !userInfo.isAdmin()) {
                throw new AuthException(AuthException.TypeEnum.EXCEPTION_AUTH.getId(), null,
                        ExceptionMessage.createExceptionMessage(AuthException.TypeEnum.EXCEPTION_AUTH.getDesc(),
                                this.getUsername(request) + " 没有此车场的权限", "权限不足:"));
            }
        }
    }

    // @Before("@annotation(com.qding.park.manager.web.power.Power)")
    // public void doBefore(JoinPoint joinPoint) {
    // Method method = getMethod(joinPoint);
    // _log.info("开始进行权限判断:{},{}",joinPoint.getTarget().getClass().getName(),method.getName());
    // HttpServletRequest request = ((ServletRequestAttributes)
    // RequestContextHolder.getRequestAttributes()).getRequest();
    // PowerInfo powerInfo=getPowerInfo(request);
    //
    //
    //
    // Power powerAnnotation = method.getAnnotation(com.qding.park.manager.web.power.Power.class);
    // String parkEl=powerAnnotation.visitPark();
    //
    // ExpressionParser parser = new SpelExpressionParser();
    // EvaluationContext exvContext = structExpContext(method, joinPoint.getArgs());
    //
    // String parkId = (String) parser.parseExpression(parkEl).getValue(exvContext, joinPoint.getTarget());
    //
    // if (StringUtils.isBlank(parkId)) {
    // if (ListUtil.isEmpty(powerInfo.getParkList()) && !powerInfo.isAdminIs()) {
    // throw new AuthException(AuthException.TypeEnum.EXCEPTION_AUTH.getId(), null,
    // ExceptionMessage.createExceptionMessage(AuthException.TypeEnum.EXCEPTION_AUTH.getDesc(),
    // this.getUsername(request) + " 没有此车场的权限", "权限不足:"));
    // }
    // } else {
    // if (!powerInfo.getParkList().contains(Integer.valueOf(parkId)) && !powerInfo.isAdminIs()) {
    // throw new AuthException(AuthException.TypeEnum.EXCEPTION_AUTH.getId(), null,
    // ExceptionMessage.createExceptionMessage(AuthException.TypeEnum.EXCEPTION_AUTH.getDesc(),
    // this.getUsername(request) + " 没有此车场的权限", "权限不足:"));
    // }
    // }
    // }
}
